package com.css.zfzx.data.primary.yhDisasterPG.service.impl;

import com.css.zfzx.data.common.Constant;
import com.css.zfzx.data.common.GenerateSiteCodeUtil;
import com.css.zfzx.data.common.ProvinceCityAreaUtil;
import com.css.zfzx.data.postgresql.fxqhPriorityPG.repository.entity.FxqhPriorityPostgresqlEntity;
import com.css.zfzx.data.postgresql.pgReconciliation.repository.PgReconciliationNativeRepository;
import com.css.zfzx.data.postgresql.yhDisasterPG.repository.YhDisasterCsRepository;
import com.css.zfzx.data.postgresql.yhDisasterPG.repository.entity.YhDisasterCsPostgresqlEntity;
import com.css.zfzx.data.primary.base.division.repository.BaseDivisionRepository;
import com.css.zfzx.data.primary.base.repository.SuperRepository;
import com.css.zfzx.data.primary.base.vo.ProxyVO11;
import com.css.zfzx.data.primary.base.vo.ProxyVO4;
import com.css.zfzx.data.primary.yhDisasterPG.repository.YhDisasterPGNativeRepository;
import com.css.zfzx.data.primary.yhDisasterPG.repository.entity.YhDisasterPGEntity;
import com.css.zfzx.data.primary.yhDisasterPG.service.YhDisasterPGService;
import com.css.zfzx.data.thirdary.jgReconciliation.repository.entity.SjtgfJghshYjSjdzbEntity;
import com.css.zfzx.data.thirdary.jgReconciliation.service.ReconciliationService;
import com.css.zfzx.data.util.DateUtil;
import com.css.zfzx.data.util.GeometryUtil;
import com.vividsolutions.jts.geom.Geometry;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description: data
 * @Author: lhl
 * @CreateDate: 2021/4/27 9:29
 */
@Log4j2
@Transactional
@Service("yhDisasterCsPGServiceImpl")
public class YhDisasterCsPGServiceImpl implements YhDisasterPGService {
    private final YhDisasterPGNativeRepository nativeRepository;
    private final YhDisasterCsRepository csRepository;
    private final PgReconciliationNativeRepository jgNativeRepository;
    private final ReconciliationService reconciliationService;
    @Autowired
    SuperRepository superRepository;
    @Autowired
    public YhDisasterCsPGServiceImpl(YhDisasterPGNativeRepository nativeRepository, YhDisasterCsRepository csRepository, PgReconciliationNativeRepository jgNativeRepository, ReconciliationService reconciliationService) {
        this.nativeRepository = nativeRepository;
        this.csRepository = csRepository;
        this.jgNativeRepository = jgNativeRepository;
        this.reconciliationService = reconciliationService;
    }
    @Autowired
    BaseDivisionRepository baseDivisionRepository;

    private static List<String> pioneerList=new ArrayList<>();
    @PostConstruct
    public void init(){
        pioneerList=baseDivisionRepository.findPioneerType();
    }
    @Override
    public void findDataCreate() {
        LocalDateTime createTime = csRepository.findCreateTime();
        //查询新增数据
        List<YhDisasterPGEntity> entities = nativeRepository.findYhDisasterPGCreate(createTime,3);
        if (entities.size() == 0) {
            System.out.println("yh_disaster_cs:时间" + new Date() + ",添加查询了数据：" + entities.size() + " 条");
            return;
        }
        List<YhDisasterCsPostgresqlEntity> saveList = new ArrayList<>();
        int flag = 0;
        String startCode = null;
        Map<String,String> errorMap=new HashMap<>();
        for (YhDisasterPGEntity entity : entities) {
            String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
            if (code == null) {
                errorMap.put(entity.getId(), "区划编码获取失败！");
                continue;
            }
            if (!pioneerList.contains(code)){
                errorMap.put(entity.getId(), "不符合122个试点县！");
                continue;
            }
            YhDisasterCsPostgresqlEntity postgresEntity = new YhDisasterCsPostgresqlEntity();
            BeanUtils.copyProperties(entity, postgresEntity);

            if (entity.getSpaceData() != null) {
                try{
                    Geometry geometry = GeometryUtil.setRecArea(entity.getSpaceData());
                    postgresEntity.setExtends1(geometry);
                }catch (Exception e){
                    e.printStackTrace();
                    errorMap.put(entity.getId(),"空间数据:{}"+entity.getSpaceData()+" 异常!");
                }
            }else {
                //errorMap.put(entity.getId(), "空间数据为空！");
                //continue;
            }

            postgresEntity.setExtends2(entity.getExtends1());
            postgresEntity.setFxpcDataidSjgl(entity.getExtends3());

            String oldSitCode = null;
            if (flag == 0) {
                flag++;
                oldSitCode = csRepository.getGenerateSiteCode();
            } else {
                oldSitCode = startCode;
            }
            String generateSiteCode = GenerateSiteCodeUtil.generateSiteCode(code, oldSitCode, "地震危险性计算点");
            startCode = generateSiteCode;
            postgresEntity.setFxpcDcdxbmSjgl(generateSiteCode);
            //根据名称获取行政编码
            if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
            }
            if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                postgresEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
            }
            if (!StringUtils.isEmpty(entity.getArea())) {
                postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                postgresEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                postgresEntity.setFxpcXzqhbmcSjgl(code);
            }
            //标识数据的当前状态，如果是新增数据，该字段为I；
            // 如果数据被更新过，该字段为U；如果数据被删除，该字段为D。
            postgresEntity.setFxpcSjztSjgl("I");
            //将创建时间转化成字符串形式
            if (entity.getCreateTime() != null) {
                postgresEntity.setFxpcCreatetimeSjgl(DateUtil.getContainsHMS(entity.getCreateTime()));
            }
            //统一都是默认040
            postgresEntity.setFxpcSshySjgl("040");
            //日期分片
            postgresEntity.setFxpcRqfpSjgl(DateUtil.getNotContainsHMS(new Date()));
            //批次号
            postgresEntity.setFxpcPchSjgl(DateUtil.getNotContainsHMS(new Date()));
            //审核流程状态
            postgresEntity.setFxpcShlcztSjgl(Constant.SHLCZT_ZZSH);
            //审核状态
            postgresEntity.setFxpcShztSjgl(Constant.SHZT_TG);
            saveList.add(postgresEntity);
        }
        long startIn = System.currentTimeMillis();
        int iterable = jgNativeRepository.batchSave1(saveList);
        long endIn = System.currentTimeMillis();
        if (errorMap.size()>0||!errorMap.isEmpty()) {
            log.error(errorMap);
        }
        System.out.println("表yh_disaster_cs:时间" + new Date() + ",插入数据：" + saveList.size() + " 条,失败："+(entities.size()-saveList.size())+" 条,用时  " + (endIn - startIn));
        update(iterable,saveList);
        SjtgfJghshYjSjdzbEntity sjtgfJghshYjSjdzbEntity = new SjtgfJghshYjSjdzbEntity();
        sjtgfJghshYjSjdzbEntity.setBmc("yh_disaster_cs");
        sjtgfJghshYjSjdzbEntity.setSjts(iterable);
        reconciliationService.saveReconciliation(sjtgfJghshYjSjdzbEntity);
    }

    @Override
    public void findDataCreate1() {

    }

    private void update(int iterable,List<YhDisasterCsPostgresqlEntity> saveList){
        List<ProxyVO11> proxyVOs=new ArrayList<>();
        for (int i=0;i<iterable;i++) {
            YhDisasterCsPostgresqlEntity pgEntity = saveList.get(i);
            ProxyVO11 proxyVO=new ProxyVO11();
            proxyVO.setId(pgEntity.getId());
            //proxyVO.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            proxyVO.setIsReportPg("1");
            proxyVOs.add(proxyVO);
        }
        superRepository.batchUpdate(proxyVOs);
    }
    @Override
    public void findDataUpdate() {
        LocalDateTime updateTime = csRepository.findUpdateTime();
        //查询新增数据
        List<YhDisasterPGEntity> entities = nativeRepository.findYhDisasterPGUpdate(updateTime,3);
        if (entities.size() == 0) {
            System.out.println("yh_disaster_cs:时间" + new Date() + ",修改查询了数据：" + entities.size() + " 条");
            return;
        }
        List<YhDisasterCsPostgresqlEntity> saveList = new ArrayList<>();
        int flag = 0;
        String startCode = null;
        Map<String,String> errorMap=new HashMap<>();
        for (YhDisasterPGEntity entity : entities) {
            String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
            if (code == null) {
                errorMap.put(entity.getId(), "区划编码获取失败！");
                continue;
            }
            if (!pioneerList.contains(code)){
                errorMap.put(entity.getId(), "不符合122个试点县！");
                continue;
            }
            YhDisasterCsPostgresqlEntity postgresEntity = new YhDisasterCsPostgresqlEntity();
            BeanUtils.copyProperties(entity, postgresEntity);

            if (entity.getSpaceData() != null) {
                try{
                    Geometry geometry = GeometryUtil.setRecArea(entity.getSpaceData());
                    postgresEntity.setExtends1(geometry);
                }catch (Exception e){
                    e.printStackTrace();
                    errorMap.put(entity.getId(),"空间数据:{}"+entity.getSpaceData()+" 异常!");
                }
            }else {
                //errorMap.put(entity.getId(), "空间数据为空！");
                //continue;
            }

            postgresEntity.setExtends2(entity.getExtends1());
            postgresEntity.setFxpcDataidSjgl(entity.getExtends3());
            String oldSitCode = null;
            if (flag == 0) {
                flag++;
                oldSitCode = csRepository.getGenerateSiteCode();
            } else {
                oldSitCode = startCode;
            }
            String generateSiteCode = GenerateSiteCodeUtil.generateSiteCode(code, oldSitCode, "地震危险性计算点");
            startCode = generateSiteCode;
            postgresEntity.setFxpcDcdxbmSjgl(generateSiteCode);
            //根据名称获取行政编码
            if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
            }
            if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                postgresEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
            }
            if (!StringUtils.isEmpty(entity.getArea())) {
                postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                postgresEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                postgresEntity.setFxpcXzqhbmcSjgl(code);
            }
            //标识数据的当前状态，如果是新增数据，该字段为I；
            // 如果数据被更新过，该字段为U；如果数据被删除，该字段为D。
            if (entity.getIsValid().equals("0")) {
                postgresEntity.setFxpcSjztSjgl("D");
            } else {
                postgresEntity.setFxpcSjztSjgl("U");
            }
            //将创建时间转化成字符串形式
            if (entity.getCreateTime() != null) {
                postgresEntity.setFxpcCreatetimeSjgl(DateUtil.getContainsHMS(entity.getCreateTime()));
            }
            if (entity.getUpdateTime() != null) {
                postgresEntity.setFxpcUpdatetimeSjgl(DateUtil.getContainsHMS(entity.getUpdateTime()));
            }
            //统一都是默认040
            postgresEntity.setFxpcSshySjgl("040");
            //日期分片
            postgresEntity.setFxpcRqfpSjgl(DateUtil.getNotContainsHMS(new Date()));
            //批次号
            postgresEntity.setFxpcPchSjgl(DateUtil.getNotContainsHMS(new Date()));
            //审核流程状态
            postgresEntity.setFxpcShlcztSjgl(Constant.SHLCZT_ZZSH);
            //审核状态
            postgresEntity.setFxpcShztSjgl(Constant.SHZT_TG);
            saveList.add(postgresEntity);
        }
        long startIn = System.currentTimeMillis();
        int iterable = jgNativeRepository.batchUpdate1(saveList);
        long endIn = System.currentTimeMillis();
        if (errorMap.size()>0||!errorMap.isEmpty()) {
            log.error(errorMap);
        }
        System.out.println("表yh_disaster_cs:时间" + new Date() + ",修改数据：" + saveList.size() + " 条,失败："+(entities.size()-saveList.size())+" 条,用时  " + (endIn - startIn));
        update(iterable,saveList);
        SjtgfJghshYjSjdzbEntity sjtgfJghshYjSjdzbEntity = new SjtgfJghshYjSjdzbEntity();
        sjtgfJghshYjSjdzbEntity.setBmc("yh_disaster_cs");
        sjtgfJghshYjSjdzbEntity.setSjts(iterable);
        reconciliationService.saveReconciliation(sjtgfJghshYjSjdzbEntity);
    }

    @Override
    public void findDataUpdate1() {

    }
}
